
package com.tools.cleanmaster.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.tools.cleanmaster.R;


@SuppressWarnings("static-access")
public class ToggleButton extends ImageView {
    private static final int NO_ALPHA = 0xFF;

    private boolean mChecked = false;
    private float mDisabledAlpha;

    private static final int[] CHECKED_STATE_SET = {
            android.R.attr.state_checked
    };

    public ToggleButton(Context context) {
        super(context);
        init(context);
    }

    public ToggleButton(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ToggleButton);
        mDisabledAlpha = a.getFloat(R.styleable.ToggleButton_disabledAlpha, 0.5f);
        a.recycle();

        init(context);
    }

    private void init(Context cxt) {
        syncBackground();
    }


    private void syncBackground() {
        if (mChecked) {
            setImageResource(R.drawable.dx_toggle_button_on);
        } else {
            setImageResource(R.drawable.dx_toggle_button_off);
        }
    }

    @Override
    protected void drawableStateChanged() {
        super.drawableStateChanged();
        Drawable bkgDrawable = getBackground();
        if (bkgDrawable != null) {
            bkgDrawable.setAlpha(isEnabled() ? NO_ALPHA : (int) (NO_ALPHA * mDisabledAlpha));
        }
        syncBackground();
    }

    @Override
    public boolean performClick() {
        if (!super.performClick()) {
            // If no OnClickListener setup, toggle this button as default
            // behavior
            toggle();
            return false;
        }
        return true;
    }

    public boolean isChecked() {
        return mChecked;
    }

    public void setChecked(boolean checked) {
        if (mChecked == checked) {
            return; // no change
        }
        mChecked = checked;
        refreshDrawableState();
        syncBackground();
    }

    public void toggle() {
        setChecked(!mChecked);
    }
}
